<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Account</title>
    <link rel="stylesheet" th:href="@{/css/custom-style.css}">
    <link rel="stylesheet" th:href="@{/webjars/bootstrap/4.1.3/css/bootstrap.min.css}">
    <link rel="stylesheet" th:href="@{/poshytip/tip-twitter/tip-twitter.css}">
    <script th:src="@{/webjars/jquery/3.3.1-1/jquery.min.js}"></script>
    <script th:src="@{/webjars/bootstrap/4.1.3/js/bootstrap.min.js}"></script>
    <script th:src="@{/poshytip/jquery.poshytip.min.js}"></script>
    <script th:src="@{/js/cropbox.js}"></script>
</head>
<body>

<div th:replace="templates::topbar(currentPage='userInfo')"></div>


<div class="container">
    <div class="row">
        <div class="col-md-3">
            <div class="card shadow-sm">
                <div class="card-body text-center">

                    <img id="userIconImg"
                         title="Click to edit your profile picture"
                         class="user-big rounded-circle cursor-pointer"
                         th:src="${session.user.userIcon}==null?@{/img/defaultIcon.png}:@{${session.user.userIcon}}"
                         src="/img/defaultIcon.png" alt="">
                    <div class="mt-2">
                        <div class="badge badge-dark">userId</div>
                        <span th:text="${session.user.userId}">1</span>
                    </div>

                </div>
                <div class="card-body">
                    <div>
                        <label>userName:</label>
                        <input id="userNameInput" class="form-control" type="text" th:value="${session.user.userName}"
                               value="Dove">
                    </div>
                    <div>
                        <label>gender:</label>
                        <select id="genderSelect" class="form-control">
                            <option value="0" th:selected="${session.user.gender==0}" selected>Secrecy</option>
                            <option value="1" th:selected="${session.user.gender==1}">Male</option>
                            <option value="2" th:selected="${session.user.gender==2}">Female</option>
                        </select>
                    </div>
                </div>
                <div class="card-body text-center">
                    <p id="saveInfo"></p>
                    <button id="saveBtn" class="btn btn-success">Save</button>
                    <button id="pwdBtn" class="btn btn-danger" data-toggle="modal" data-target="#pwdModal">
                        Edit Password
                    </button>
                </div>
            </div>
        </div>
        <div class="col-md-9">
            <div class="card shadow-sm">
                <div class="card-body">
                    <h3 class="d-inline-flex">My Videos</h3>
                    <div class="float-right">
                        <a th:href="@{/upload}"><button class="btn btn-primary">New Video</button></a>
                    </div>
                    <hr>
                    <div id="videoCards">

                    </div>

                </div>
                <div class="card-body text-center">
                    <div id="videoNav">

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>


<!-- Password Change Modal -->
<div class="modal fade" id="pwdModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle"
     aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalCenterTitle">Edit Password</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label>Current Password</label>
                    <input id="currentPassword" type="password" class="form-control" placeholder="current password">
                </div>
                <div class="form-group">
                    <label>New Password</label>
                    <input id="newPassword" type="password" class="form-control" placeholder="new password">
                </div>
                <div class="form-group">
                    <label>Confirm Password</label>
                    <input id="confirmPassword" type="password" class="form-control" placeholder="confirm password">
                </div>
                <p id="pwdErrorMsg" class="text-danger"></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button id="pwdSaveBtn" type="button" class="btn btn-primary">Save changes</button>
            </div>
        </div>
    </div>
</div>

<!-- confirm modal -->
<div class="modal fade" id="confirmModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle"
     aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalCenterTitle">Success</h5>
            </div>
            <div class="modal-body">
                <p>Password changed successfully, click confirm to login with new password!</p>
            </div>
            <div class="modal-footer">
                <button id="confirmBtn" type="button" class="btn btn-primary">Confirm</button>
            </div>
        </div>
    </div>
</div>

<!-- profile picture edit modal -->
<div class="modal fade" id="iconEditModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle"
     aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Profile Picture</h5>
            </div>
            <div class="modal-body">
                <div class="container">
                    <div class="imageBox">
                        <div class="thumbBox"></div>
                        <div class="spinner" style="display: none">Loading...</div>
                    </div>
                    <div class="action">
                        <div class="new-contentarea tc">
                            <a href="javascript:void(0)" class="upload-img">
                                <label for="upload-file">Upload Image</label>
                            </a>
                            <input type="file" class="" name="upload-file" id="upload-file"/>
                        </div>
                        <input type="button" id="btnCrop" class="Btnsty_peyton" value="Crop">
                        <input type="button" id="btnZoomIn" class="Btnsty_peyton" value="+">
                        <input type="button" id="btnZoomOut" class="Btnsty_peyton" value="-">
                    </div>
                    <div class="cropped"></div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button id="iconEditBtn" type="button" class="btn btn-primary">Confirm</button>
            </div>
        </div>
    </div>
</div>


<script>

    var userIcon = $('#userIconImg');
    var currentPage = 1;

    function gotoPage(pn) {
        $.ajax({
            url: "/videos/" + [[${session.user.userId}]],
            data: "pn=" + pn,
            type: "GET",
            success: function (result) {
                currentPage = pn;
                buildCards(result);
                buildVideoNav(result);
            }
        });
    }

    function buildCards(result) {
        var count = 0;
        var videos = result.extras.pageInfo.list;
        var user = result.extras.user;
        var videoCards = $('#videoCards');
        videoCards.empty();
        var rowDiv = $('<div></div>').addClass('row').addClass('mb-2');
        $.each(videos, function (index, item) {
            count++;
            var cardDiv = "    <div class=\"col-sm-4\">\n" +
                "        <div class=\"card shadow\">\n" +
                "            <div class=\"card-body text-center\">\n" +
                "                <a href=\"/vid/" + item.videoId + "\">\n" +
                "                    <div>\n" +
                "                        <img src=" + (item.cover === null ? "/img/defaultVideoCover.png" : item.cover) + " class=\"video-cover\">\n" +
                "                        <p class=\"mt-2 font-weight-bold card-text\" style=\"font-size: 14px\">" +
                    item.videoName +
                "                    </div>\n" +
                "                </a>\n" +
                "                <hr>\n" +
                "                <a href=\"/uid/" + user.userId + "\">\n" +
                "                    <div class=\"text-right mr-2\">\n" +
                "                        <div class=\"d-inline-block\" style=\"font-size: 12px\">\n" +
                "                            <span>" + user.userName + "</span>\n" +
                "                            <p>" + item.uploadTime.slice(0, 10) + "</p>\n" +
                "                        </div>\n" +
                "                        <img src=" + user.userIcon  +
                "                             class=\"user-small rounded-circle img-fluid\"\n" +
                "                             style=\"vertical-align: baseline\">\n" +
                "                    </div>\n" +
                "                </a>\n" +
                "            </div>\n" +
                "        </div>\n" +
                "    </div>\n";

            rowDiv.append(cardDiv);
            if (count === 3) {
                count = 0;
                rowDiv.appendTo(videoCards);
                rowDiv = $('<div></div>').addClass('row').addClass('mb-2');
            }
        });
        if (count !== 0) {
            rowDiv.appendTo(videoCards);
        }

    }

    function buildVideoNav(result) {
        $("#videoNav").empty();
        var pageInfo = result.extras.pageInfo;
        var ul = $("<ul></ul>").addClass("pagination");
        var firstPageLi = $("<li></li>").addClass('page-item').append($("<a></a>").addClass('page-link')
            .append("Index").attr("href", "#"));
        var prePageLi = $("<li></li>").addClass('page-item').append($("<a></a>").addClass('page-link')
            .append($("<span></san>").attr("aria-hidden", "true")
                .append("&laquo;")).attr("href", "#"));
        if (!pageInfo.hasPreviousPage) {
            prePageLi.addClass("disabled");
            firstPageLi.addClass("disabled");
        } else {
            firstPageLi.click(function () {
                gotoPage(1);
            });
            prePageLi.click(function () {
                gotoPage(pageInfo.pageNum - 1);
            });
        }
        var nextPageLi = $("<li></li>").addClass('page-item').append($("<a></a>").addClass('page-link')
            .append($("<span></san>").attr("aria-hidden", "true")
                .append("&raquo;")).attr("href", "#"));
        var lastPageLi = $("<li></li>").addClass('page-item').append($("<a></a>").addClass('page-link')
            .append("Last").attr("href", "#"));
        if (!pageInfo.hasNextPage) {
            nextPageLi.addClass("disabled");
            lastPageLi.addClass("disabled");
        } else {
            nextPageLi.click(function () {
                gotoPage(pageInfo.pageNum + 1);
            });
            lastPageLi.click(function () {
                gotoPage(pageInfo.pages);
            });
        }
        ul.addClass('justify-content-center').append(firstPageLi).append(prePageLi);
        $.each(pageInfo.navigatepageNums, function (index, item) {
            var numLi = $("<li></li>").addClass('page-item').append($("<a></a>").addClass('page-link')
                .append(item).attr("href", "#"));
            if (pageInfo.pageNum == item) {
                numLi.addClass("active");
            }
            numLi.click(function () {
                gotoPage(item);
            });
            ul.append(numLi);
        });
        ul.append(nextPageLi).append(lastPageLi);
        var nav = $("<nav></nav>")
            .attr("aria-label", "Page navigation").append(ul);
        nav.appendTo("#videoNav");
    }

    $(function () {
        gotoPage(1);
    });

    $('#saveBtn').click(function () {
        var userName = $('#userNameInput').val();
        var gender = $('#genderSelect').val();
        var saveInfo = $('#saveInfo');
        saveInfo.empty();
        saveInfo.removeClass();
        var uploadParam = [
            {name: 'userName', value: userName},
            {name: 'gender', value: gender}
        ];
        $.ajax({
            url: '/user/info',
            type: 'PUT',
            data: $.param(uploadParam),
            success: function (result) {
                if (result.code === 0) {
                    saveInfo.addClass('text-success');
                    saveInfo.text('Save Successfully');
                } else {
                    saveInfo.addClass('text-danger');
                    saveInfo.text(result.msg);
                }
            }
        });
    });

    $('#pwdSaveBtn').click(function () {
        var pwdError = $('#pwdErrorMsg');
        var currentPwd = $('#currentPassword').val();
        var newPwd = $('#newPassword').val();
        var confirmPwd = $('#confirmPassword').val();
        pwdError.empty();
        if (confirmPwd !== newPwd) {
            pwdError.text('confirm password is not the same as the new password, please check');
            return
        }
        var uploadParam = [
            {name: 'currentPassword', value: currentPwd},
            {name: 'newPassword', value: newPwd}
        ];
        $.ajax({
            url: '/user/pwd',
            method: 'PUT',
            data: $.param(uploadParam),
            success: function (result) {
                if (result.code === 0) {
                    $('#confirmModal').modal({
                        backdrop: 'static',
                        show: true,
                        keyboard: false
                    });
                } else {
                    pwdError.text(result.msg);
                }
            }
        });
    });

    $('#confirmBtn').click(function () {
        $(location).attr('href', '/login');
    });

    userIcon.poshytip({
        className: 'tip-twitter',
        showTimeout: 1,
        alignTo: 'target',
        alignX: 'center',
        offsetY: 5,
        allowTipHover: false,
        fade: false
    });

    userIcon.click(function () {
        $('#iconEditModal').modal({
            backdrop: 'static',
            show: true,
            keyboard: false
        });
    });

    // cropbox
    $(window).on('load', function () {
        var options = {
            thumbBox: '.thumbBox',
            spinner: '.spinner',
            imgSrc: '/img/defaultIcon.png'
        };
        var cropper = $('.imageBox').cropbox(options);
        $('#upload-file').on('change', function () {
            var reader = new FileReader();
            reader.onload = function (e) {
                options.imgSrc = e.target.result;
                cropper = $('.imageBox').cropbox(options);
            };
            reader.readAsDataURL(this.files[0]);
            this.files = [];
        });
        $('#btnCrop').on('click', function () {
            var img = cropper.getDataURL();
            var cropped = $('.cropped');
            cropped.html('');
            cropped.append('<img src="' + img + '" align="absmiddle" style="width:64px;margin-top:4px;border-radius:64px;box-shadow:0px 0px 12px #7E7E7E;" ><p>64px*64px</p>');
            cropped.append('<img src="' + img + '" align="absmiddle" style="width:128px;margin-top:4px;border-radius:128px;box-shadow:0px 0px 12px #7E7E7E;"><p>128px*128px</p>');
            cropped.append('<img src="' + img + '" align="absmiddle" style="width:180px;margin-top:4px;border-radius:180px;box-shadow:0px 0px 12px #7E7E7E;"><p>180px*180px</p>');
        });
        $('#btnZoomIn').on('click', function () {
            cropper.zoomIn();
        });
        $('#btnZoomOut').on('click', function () {
            cropper.zoomOut();
        });
        $('#iconEditBtn').on('click', function () {
            var img = cropper.getBlob();
            var uploadData = new FormData();
            uploadData.append("imageFile", img);
            $.ajax({
                url: "/uploadIcon",
                data: uploadData,
                type: "post",
                processData: false,
                contentType: false,
                success: function (result) {
                    if (result.code === 0) {
                        window.location.reload()
                    } else {
                        alert(result.msg);
                    }
                }
            })
        })
    });



</script>

</body>
</html>